import type { TableColumnCtx } from 'element-plus'
import {
  addElectricityConfig,
  checkElectricityConfig,
  deleteElectricityConfig,
  getElectricityConfig,
  getElectricityConfigByPage,
  updateElectricityConfig,
} from '@/api/modules/electricity'
import { PAGING } from '@/constant'

export enum ELECTRICITY_CONFIG_TYPES {
  /** 尖 */
  TIP = 1,
  /** 峰 */
  PEAK,
  /** 平 */
  FLAT,
  /** 谷 */
  VALLEY,
}

export interface Config {
  startTime: string
  endTime: string
  type: ELECTRICITY_CONFIG_TYPES
  price: number | string
}

export interface ElectricityConfig {
  time: string
  tipList: Config[]
  peakList: Config[]
  flatList: Config[]
  valleyList: Config[]
  creationName: string
  creationTime: string
}

export type ColumnType = {
  label: string
  prop: string
} & Partial<Omit<TableColumnCtx<ElectricityConfig>, 'label' | 'prop'>>

export type OmitCreationElectricityConfig = Omit<ElectricityConfig, 'creationName' | 'creationTime'>
export function getDefaults(): OmitCreationElectricityConfig {
  return {
    time: '',
    tipList: [
      {
        startTime: '',
        endTime: '',
        type: ELECTRICITY_CONFIG_TYPES.TIP,
        price: '',
      },
    ],
    peakList: [
      {
        startTime: '',
        endTime: '',
        type: ELECTRICITY_CONFIG_TYPES.PEAK,
        price: '',
      },
    ],
    flatList: [
      {
        startTime: '',
        endTime: '',
        type: ELECTRICITY_CONFIG_TYPES.FLAT,
        price: '',
      },
    ],
    valleyList: [
      {
        startTime: '',
        endTime: '',
        type: ELECTRICITY_CONFIG_TYPES.VALLEY,
        price: '',
      },
    ],
  }
}

export function getListKey(type: ELECTRICITY_CONFIG_TYPES) {
  let key: 'tipList' | 'peakList' | 'flatList' | 'valleyList' = 'tipList'
  switch (type) {
    case ELECTRICITY_CONFIG_TYPES.TIP: {
      key = 'tipList'
      break
    }
    case ELECTRICITY_CONFIG_TYPES.PEAK: {
      key = 'peakList'
      break
    }
    case ELECTRICITY_CONFIG_TYPES.FLAT: {
      key = 'flatList'
      break
    }
    case ELECTRICITY_CONFIG_TYPES.VALLEY: {
      key = 'valleyList'
      break
    }
  }
  return key
}

export function useElectricPriceConfigs() {
  const [loading, setLoading] = useState(false)
  const [saving, setSaving] = useState(false)
  const columns: ColumnType[] = [
    { label: '开始时间', prop: 'time', width: 150, fixed: true },
    { label: '尖', prop: 'tipList', minWidth: 200 },
    { label: '峰', prop: 'peakList', minWidth: 200 },
    { label: '平', prop: 'flatList', minWidth: 200 },
    { label: '谷', prop: 'valleyList', minWidth: 200 },
    { label: '创建人', prop: 'creationName' },
    { label: '创建时间', prop: 'creationTime', minWidth: 150 },
  ]
  const [lists, setLists] = useShallowState<ElectricityConfig[]>([])
  const pagination = reactive({
    pageNumber: 1,
    pageSize: PAGING.PAGE_SIZES[0]!,
    total: 0,
  })

  async function queryElectricPriceConfigs(time: string) {
    setLoading(true)
    try {
      const { data } = await getElectricityConfig(time);
      (data || []).forEach((item: any) => {
        item.creationTime = dayjs(item.creationTime).format('YYYY-MM-DD HH:mm:ss')
      })
      setLists(data)
    }
    catch (e) {
      console.warn(e)
    }
    finally {
      setLoading(false)
    }
  }

  async function queryElectricPriceConfigsByPage(params: {
    pageNumber: number
    pageSize: number
    time: string
  }) {
    setLoading(true)
    try {
      const { data } = await getElectricityConfigByPage(params);
      (data.records || []).forEach((item: any) => {
        item.creationTime = dayjs(item.creationTime).format('YYYY-MM-DD HH:mm:ss')
        item.tipList = item.tipList || []
        item.peakList = item.peakList || []
        item.flatList = item.flatList || []
        item.valleyList = item.valleyList || []
      })
      setLists(data.records || [])
      pagination.total = data.total
    }
    catch (e) {
      console.warn(e)
    }
    finally {
      setLoading(false)
    }
  }

  async function confirmDel() {
    return ElMessageBox.confirm(
      '确认要删除该电价配置吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      },
    )
  }

  async function delElectricityConfig(time: string) {
    const res = await confirmDel().catch(() => {})
    if (res !== 'confirm')
      return
    try {
      await deleteElectricityConfig(time)
      ElMessage.success('删除成功')
      setLists(
        unref(lists).filter(v => v.time !== time),
      )
    }
    catch (e) {
      console.warn(e)
    }
  }

  function editElectricityConfig(data: OmitCreationElectricityConfig) {
    return updateElectricityConfig(data)
  }

  function saveElectricityConfig(data: OmitCreationElectricityConfig) {
    return addElectricityConfig(data)
  }

  async function hasConfig(time: string) {
    try {
      const { data } = await checkElectricityConfig(time)
      if (data) {
        ElMessage.warning('该时间已存在电价配置')
      }
      return data
    }
    catch (e) {
      console.warn(e)
    }
  }

  return {
    loading,
    lists,
    columns,
    pagination,
    saving,
    setSaving,
    queryElectricPriceConfigs,
    queryElectricPriceConfigsByPage,
    delElectricityConfig,
    editElectricityConfig,
    saveElectricityConfig,
    hasConfig,
  }
}
